﻿using System.Collections.Generic;
using Duality;
using Duality.Components;
using Duality.Components.Renderers;
using Duality.Resources;
using OpenTK;

namespace ClientApp
{
	[RequiredComponent(typeof(Transform))]
	public class Headquarter : Creature
	{
		public override float PhysicalBoundRad
		{
			get { return 70.0f; }
		}

		public override void OnInit(Component.InitContext context)
		{
			base.OnInit(context);
			if (context == InitContext.Activate) this.PlayerId.GetPlayer().Hq = this;
		}
		public override void OnShutdown(Component.ShutdownContext context)
		{
			base.OnShutdown(context);
			if (context == ShutdownContext.Deactivate && this.PlayerId.GetPlayer().Hq == this) this.PlayerId.GetPlayer().Hq = null;
		}
		public List<Warrior> SpawnWarriors(ContentRef<Prefab> stuff, int count)
		{
			Headquarter targetHq = this.PlayerId.Opposing().GetPlayer().Hq;

			List<Warrior> objList = new List<Warrior>(count);
			for (int i = 0; i < count; i++)
			{
				GameObject warriorObj = stuff.Res.Instantiate();
				Warrior warriorCmp = warriorObj.GetComponent<Warrior>();

				Vector2 startPos = this.GameObj.Transform.Pos.Xy + MathF.Rnd.NextVector2(100.0f);
				warriorObj.Transform.Pos = new Vector3(startPos.X, startPos.Y, -1.0f);

				if (targetHq != null)
				{
					Vector2 targetHqVec = targetHq.GameObj.Transform.Pos.Xy - this.GameObj.Transform.Pos.Xy;
					warriorObj.Transform.Angle = MathF.Angle(targetHqVec.X, targetHqVec.Y);
				}

				warriorCmp.PlayerId = this.PlayerId;
				(warriorObj.Renderer as SpriteRenderer).ColorTint = this.PlayerId.GetUnitColor();

				objList.Add(warriorCmp);
				Scene.Current.RegisterObj(warriorObj);
			}
			return objList;
		}
		public override void Die()
		{
			base.Die();
			// create explosion
			for (int i = 3; i > 0; i--)
			{
				GameObject bamAnim = GameRes.Data.Gamedata.BamAnim_Prefab.Res.Instantiate();
				bamAnim.Transform.Pos = this.GameObj.Transform.Pos - Vector3.UnitZ + new Vector3(MathF.Rnd.NextVector2(25.0f, 100.0f));
				bamAnim.Transform.Vel = -Vector3.UnitZ * MathF.Rnd.NextFloat(0.15f, 0.35f);
				bamAnim.Transform.Angle = MathF.Rnd.NextFloat(0.0f, MathF.RadAngle360);
				bamAnim.GetComponent<BamAnim>().BaseSize = MathF.Rnd.Next(96, 128);
				Scene.Current.RegisterObj(bamAnim);
			}
			// create splatter
			for (int i = 5; i > 0; i--)
			{
				GameObject splatter = GameRes.Data.Gamedata.Splatter_Prefab.Res.Instantiate();
				splatter.Transform.Pos = this.GameObj.Transform.Pos + Vector3.UnitZ + new Vector3(MathF.Rnd.NextVector2(25.0f, 100.0f));;
				splatter.GetComponent<Splatter>().BaseSize = MathF.Rnd.Next(64, 128);
				splatter.GetComponent<AnimSpriteRenderer>().ColorTint = this.PlayerId.GetUnitColor();
				Scene.Current.RegisterObj(splatter);
			}
		}
	}
}
